package com.fengyunhe.manager.web;

import com.fengyunhe.manager.service.AdminResetPwdService;
import com.fengyunhe.common.AppContext;
import com.fengyunhe.common.bean.EmailVo;
import com.fengyunhe.manager.service.EmailNotifyService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 密码找回
 *
 * @author yangyan
 *         Created by Administrator on 2014/11/6.
 */
@Controller
@RequestMapping("/account/getPwd")
public class PasswordRetakeController extends AdminBaseController {
    private static final String MODULE_NAME = "密码找回";
    private static final Log logger = LogFactory.getLog(PasswordRetakeController.class);

    @Autowired
    private AdminResetPwdService retakeService;
    @Autowired
    private EmailNotifyService emailNotifyService;

    @Value("#{config['stmp_username']}")
    private String sender;

    /**
     * 提交密码找回申请请求
     *
     * @param request
     * @param email
     * @return
     */
    @ResponseBody
    @RequestMapping("/retake.do")
    public Map<String, Object> applyForPassword(HttpServletRequest request, String email) {
        Map<String, Object> result = new HashMap<String, Object>();

        try {
            // 验证邮箱地址，并发送邮件
            String token = this.retakeService.checkUserEmaiAndSetRedis(email);

            if (StringUtils.isNotBlank(token)) {
                String resetPwdUrl = AppContext.getSiteBaseUrl() + "/account/getPwd/resetPwd.do?tk=" + token;
                System.out.println("resetPwdUrl=" + resetPwdUrl);

                //发送邮件
                EmailVo emailVo = new EmailVo();
                emailVo.setSender(sender);
                emailVo.setReceivers(new String[]{email});
                emailVo.setSubject("重置密码——TradingDesk");
                emailVo.setEmailContent("请点击下面的连接，或者复制出该链接地址，打开浏览器页面进行重置密码！\n\n\n\t\t\t"
                        + resetPwdUrl
                        + "\n\n\n为了安全期间，请勿传播给他人使用。谢谢!!!打死都不能把地址给别人哦！");

                try {
                    emailNotifyService.sendEmailMessageOfSimpleText(emailVo, new Date());
                    result.put("success", true);
                    result.put("msg", "密码重置请求提交成功，请登录邮箱使用链接地址进行修改密码！邮件有效期为30分钟。");
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("msg", "邮件发送异常，请联系管理员。");
                    logger.error("邮件发送异常", e);
                }
            } else {
                result.put("success", false);
                result.put("msg", "您输入的邮箱不存在，请重新输入!!!");
            }

            System.out.println("token=" + token + ", result=" + result);
        } catch (Exception e) {
            result.put("msg", "非法操作！");
            result.put("success", false);
            result.put("status", 0);
            logger.error("密码找回发生异常！", e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 密码找回页面跳转
     *
     * @param tk
     * @return
     */
    @RequestMapping("/resetPwd.do")
    public String resetMailPage(HttpServletRequest request, String tk) {
        request.setAttribute("tk", tk);
        boolean isExists = this.retakeService.isEmailExists(tk);

        String url = "/admin/frame.do";
        if (isExists) {
            url = "/admin/newmedia/resetPwd";
        }
        return url;
    }

    /**
     * 重置用户密码
     *
     * @param request
     * @param tk
     * @param password
     * @param repassword
     * @return
     */
    @ResponseBody
    @RequestMapping("/udpPwd.do")
    public Map<String, Object> passwordRetake(HttpServletRequest request, String password, String repassword, String tk) {
        Map<String, Object> result = new HashMap<String, Object>();

        try {
            if (StringUtils.equals(password, repassword)) {
                boolean flag = this.retakeService.resetUserPassword(password, tk);
                if (!flag) {
                    result.put("msg", "存在非法操作！");
                    result.put("success", false);
                } else {
                    result.put("url", AppContext.getSiteBaseUrl() + "/admin/frame.do");
                    result.put("msg", "密码成功设置，5秒后页面自动跳转，请重新登录！谢谢");
                    result.put("success", true);
                }
            } else {
                result.put("msg", "两次输入密码不一致!请检查，重新输入....");
                result.put("success", false);
            }
        } catch (Exception e) {
            result.put("msg", "非法操作！");
            result.put("success", false);
            logger.error("密码找回发生异常！", e);
        }
        return result;
    }


}
